package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.until.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil  jwtUtil;
    Map<String,Object> map = new HashMap<>();

    @RequestMapping("/selectUser")
    public Result selectUser() {
        return Result.success(userService.findAll());
    }

    @PostMapping("/findUser")
    public Result findUser(String username, String password) {
        User user = userService.findUser(username, password);
        System.out.println(user);
        if (user!= null) {
            String token = jwtUtil.generateToken(user.getUsername());
            jwtUtil.storeToken(token, user.getUsername());
            map.put("token", token);
            map.put("user", user);
            return Result.success(map);
        } else {
            return  Result.error("用户名或者密码错误");
        }
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if(userService.register(user)){
            return Result.success("注册成功");
        } else {
            return Result.error("用户已存在");
        }
    }
    @PostMapping("/sendEmail")
    public Result sendEmail(String email) {
        if (userService.findUserByEmail(email) <= 0) {
            return Result.error("邮箱不存在");
        }
        userService.sendEmail(email);
        return Result.success("发送成功");
    }

    // 修改密码接口
    @PostMapping("/updateUser")
    public Result updateUser(@RequestParam String email,
                             @RequestParam String code,
                             @RequestParam String newPassword) {
        // 判断验证码是否正确
        if (userService.findEmail(email, code)) {
            // 进行密码修改
            if (userService.updateUser(email, newPassword) > 0) {
                return Result.success("修改成功");
            }
            return Result.error("修改失败");
        } else {
            return Result.error("验证码不正确");
        }
    }
}